const { asyncHandler } = require('../middleware/errorHandler');
const { success, error, paginate, paginateResponse } = require('../utils/common');
const Lesson = require('../models/Lesson');
const LessonView = require('../models/LessonView');
const Course = require('../models/Course');
const CourseUser = require('../models/CourseUser');
const { Op } = require('sequelize');

class LessonController {
  /**
   * 获取课程的所有课时
   */
  static getCourseLessons = asyncHandler(async (req, res) => {
    const { course_id } = req.params;
    const { user_id } = req.query;

    // 验证课程是否存在
    const course = await Course.findByPk(course_id);
    if (!course) {
      return res.status(404).json(error('课程不存在'));
    }

    // 如果提供了用户ID，验证用户是否购买了该课程
    if (user_id) {
      const courseUser = await CourseUser.findOne({
        where: { user_id, course_id }
      });
      if (!courseUser) {
        return res.status(403).json(error('您未购买此课程'));
      }
    }

    // 获取课时列表
    const lessons = await Lesson.findAll({
      where: { 
        course_id,
        status: 'published'
      },
      attributes: [
        'id', 'title', 'description', 'duration', 'sort_order',
        'is_free', 'status', 'created_at'
      ],
      order: [['sort_order', 'ASC'], ['created_at', 'ASC']]
    });

    // 如果提供了用户ID，获取观看记录
    let lessonViews = [];
    if (user_id) {
      lessonViews = await LessonView.findAll({
        where: { user_id, course_id },
        attributes: [
          'lesson_id', 'watch_time', 'progress', 'is_completed',
          'last_position', 'watch_count', 'last_watch_at'
        ]
      });
    }

    // 合并课时信息和观看记录
    const lessonsWithViews = lessons.map(lesson => {
      const view = lessonViews.find(v => v.lesson_id === lesson.id);
      return {
        ...lesson.toJSON(),
        view: view ? {
          watch_time: view.watch_time,
          progress: view.progress,
          is_completed: view.is_completed,
          last_position: view.last_position,
          watch_count: view.watch_count,
          last_watch_at: view.last_watch_at
        } : null
      };
    });

    res.json(success(lessonsWithViews, '获取成功'));
  });

  /**
   * 获取课时详情和回放链接
   */
  static getLessonDetail = asyncHandler(async (req, res) => {
    const { course_id, lesson_id } = req.params;
    const { user_id } = req.query;

    // 验证课时是否存在
    const lesson = await Lesson.findOne({
      where: { 
        id: lesson_id,
        course_id,
        status: 'published'
      },
      include: [
        {
          model: Course,
          as: 'course',
          attributes: ['id', 'title', 'cover', 'price', 'is_free']
        }
      ]
    });

    if (!lesson) {
      return res.status(404).json(error('课时不存在'));
    }

    // 如果提供了用户ID，验证用户是否有权限观看
    if (user_id) {
      // 检查用户是否购买了课程
      const courseUser = await CourseUser.findOne({
        where: { user_id, course_id }
      });

      if (!courseUser && !lesson.is_free) {
        return res.status(403).json(error('您未购买此课程，无法观看此课时'));
      }
    }

    // 获取观看记录
    let viewRecord = null;
    if (user_id) {
      viewRecord = await LessonView.findOne({
        where: { user_id, course_id, lesson_id }
      });
    }

    // 构建回放数据
    const replayData = {
      lesson: {
        id: lesson.id,
        title: lesson.title,
        description: lesson.description,
        content: lesson.content,
        duration: lesson.duration,
        is_free: lesson.is_free,
        attachments: lesson.attachments,
        subtitles: lesson.subtitles
      },
      course: lesson.course ? {
        id: lesson.course.id,
        title: lesson.course.title,
        cover: lesson.course.cover
      } : null,
      replay: {
        video_url: lesson.video_url,
        replay_url: lesson.replay_url,
        quality: ['720p', '1080p'],
        chapters: [
          { time: 0, title: '开始' },
          { time: Math.floor(lesson.duration * 0.25), title: '第一部分' },
          { time: Math.floor(lesson.duration * 0.5), title: '第二部分' },
          { time: Math.floor(lesson.duration * 0.75), title: '第三部分' },
          { time: lesson.duration, title: '结束' }
        ]
      },
      view_record: viewRecord ? {
        watch_time: viewRecord.watch_time,
        progress: viewRecord.progress,
        is_completed: viewRecord.is_completed,
        last_position: viewRecord.last_position,
        watch_count: viewRecord.watch_count,
        last_watch_at: viewRecord.last_watch_at
      } : null
    };

    res.json(success(replayData, '获取成功'));
  });

  /**
   * 更新观看进度
   */
  static updateWatchProgress = asyncHandler(async (req, res) => {
    const { course_id, lesson_id } = req.params;
    const { user_id, watch_time, progress, position } = req.body;

    if (!user_id) {
      return res.status(400).json(error('用户ID不能为空'));
    }

    // 验证用户是否购买了课程
    const courseUser = await CourseUser.findOne({
      where: { user_id, course_id }
    });

    if (!courseUser) {
      return res.status(403).json(error('您未购买此课程'));
    }

    // 验证课时是否存在
    const lesson = await Lesson.findOne({
      where: { id: lesson_id, course_id }
    });

    if (!lesson) {
      return res.status(404).json(error('课时不存在'));
    }

    // 查找或创建观看记录
    let [viewRecord, created] = await LessonView.findOrCreate({
      where: { user_id, course_id, lesson_id },
      defaults: {
        watch_time: 0,
        progress: 0,
        is_completed: false,
        last_position: 0,
        watch_count: 1,
        first_watch_at: new Date(),
        last_watch_at: new Date()
      }
    });

    // 更新观看记录
    const updateData = {
      last_watch_at: new Date()
    };

    if (watch_time !== undefined) {
      updateData.watch_time = viewRecord.watch_time + watch_time;
    }

    if (progress !== undefined) {
      updateData.progress = Math.min(100, Math.max(0, progress));
      
      // 如果进度达到90%以上，标记为完成
      if (progress >= 90 && !viewRecord.is_completed) {
        updateData.is_completed = true;
      }
    }

    if (position !== undefined) {
      updateData.last_position = Math.max(0, position);
    }

    if (!created) {
      updateData.watch_count = viewRecord.watch_count + 1;
    }

    await viewRecord.update(updateData);

    // 更新课程观看进度
    const totalLessons = await Lesson.count({
      where: { course_id, status: 'published' }
    });

    const completedLessons = await LessonView.count({
      where: { 
        user_id, 
        course_id,
        is_completed: true
      }
    });

    const courseProgress = totalLessons > 0 ? Math.round((completedLessons / totalLessons) * 100) : 0;

    await courseUser.update({
      progress: courseProgress,
      completed_lessons: completedLessons,
      total_watch_time: (courseUser.total_watch_time || 0) + (watch_time || 0),
      last_watch_at: new Date()
    });

    res.json(success({
      lesson_progress: updateData.progress || viewRecord.progress,
      course_progress: courseProgress,
      is_completed: updateData.is_completed || viewRecord.is_completed
    }, '进度更新成功'));
  });

  /**
   * 获取学生观看统计
   */
  static getStudentWatchStats = asyncHandler(async (req, res) => {
    const { user_id } = req.params;
    const { course_id, start_date, end_date } = req.query;

    // 构建查询条件
    const where = { user_id };
    if (course_id) where.course_id = course_id;
    
    if (start_date && end_date) {
      where.last_watch_at = {
        [Op.between]: [new Date(start_date), new Date(end_date)]
      };
    }

    // 获取观看统计
    const stats = await LessonView.findAll({
      where,
      include: [
        {
          model: Course,
          as: 'course',
          attributes: ['id', 'title', 'cover']
        },
        {
          model: Lesson,
          as: 'lesson',
          attributes: ['id', 'title', 'duration']
        }
      ],
      attributes: [
        'id', 'course_id', 'lesson_id', 'watch_time', 'progress',
        'is_completed', 'watch_count', 'last_watch_at'
      ],
      order: [['last_watch_at', 'DESC']]
    });

    // 计算总统计
    const totalStats = {
      total_watch_time: stats.reduce((sum, s) => sum + s.watch_time, 0),
      total_lessons: stats.length,
      completed_lessons: stats.filter(s => s.is_completed).length,
      total_watch_count: stats.reduce((sum, s) => sum + s.watch_count, 0),
      average_progress: stats.length > 0 ? 
        Math.round(stats.reduce((sum, s) => sum + parseFloat(s.progress), 0) / stats.length) : 0
    };

    res.json(success({
      stats: stats.map(s => ({
        ...s.toJSON(),
        course: s.course ? {
          id: s.course.id,
          title: s.course.title,
          cover: s.course.cover
        } : null,
        lesson: s.lesson ? {
          id: s.lesson.id,
          title: s.lesson.title,
          duration: s.lesson.duration
        } : null
      })),
      total_stats: totalStats
    }, '获取成功'));
  });
}

module.exports = LessonController; 